﻿using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Commands.Indicies
{
    /// <summary>
    /// Command to detect the existance of foreign keys in databases.
    /// </summary>
    public static class ExistsCommand
    {
        private const string Sql = @"SHOW INDEXES FROM `{0}`;";

        /// <summary>
        /// Determines is the specified <see cref="Index"/> exists in the underlying database.
        /// </summary>
        /// <param name="index">The foreign key.</param>
        /// <param name="connection">The connection.</param>
        /// <returns></returns>
        public static bool Execute(Index index, Connection connection)
        {
            var exists = false;

            using (var db = connection.Open())
            {
                using (var command = db.CreateCommand())
                {
                    command.CommandText = string.Format(Sql, index.Table);

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var keyName = reader["Key_name"].ToString();

                            if (string.Compare(keyName, index.Name, true) != 0) continue;

                            exists = true;

                            break;
                        }

                        
                    }
                }
            }

            return exists;                
        }

    }
}